package org.example;

import bean.DB;
import bean.ResponseUtils;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.UUID;

@WebServlet("/managerRegServlet")
public class managerRegServlet extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取表单数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String confirmPassword = request.getParameter("confirmPassword");

        // 校验密码是否一致
        if (password == null || confirmPassword == null || !password.equals(confirmPassword)) {
            ResponseUtils.sendResponse(response, "密码和确认密码不一致，请重新输入", "managerReg.jsp");
            return;
        }

        // 创建数据库连接
        DB db = new DB();
        String query = "SELECT id FROM users WHERE username = ?";
        String updateQuery = "UPDATE users SET adminkey = ? WHERE username = ?";

        try (Connection conn = db.createConn(); PreparedStatement pstmt = conn.prepareStatement(query)) {
            pstmt.setString(1, username); // 查找用户名是否存在
            ResultSet rs = pstmt.executeQuery();

            // 如果该用户名已经存在
            if (rs.next()) {
                // 生成管理员密钥（使用UUID）
                String adminKey = UUID.randomUUID().toString();

                // 更新 users 表，设置该用户的 admin_key
                try (PreparedStatement updatePstmt = conn.prepareStatement(updateQuery)) {
                    updatePstmt.setString(1, adminKey); // 设置管理员密钥
                    updatePstmt.setString(2, username); // 设置用户名
                    int rowsUpdated = updatePstmt.executeUpdate();

                    if (rowsUpdated > 0) {
                        ResponseUtils.sendResponse(response, "管理员密钥生成成功，欢迎进入管理员界面", "manager.jsp");
                    } else {
                        ResponseUtils.sendResponse(response, "密钥生成失败，请稍后重试", "managerReg.jsp");
                    }
                }

            } else {
                ResponseUtils.sendResponse(response, "账户不存在，请确认用户名", "managerReg.jsp");
            }

        } catch (SQLException e) {
            e.printStackTrace();
            ResponseUtils.sendResponse(response, "数据库连接错误，请稍后重试", "managerReg.jsp");
        }
    }
}
